#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import time

from clickhouse import log
from common.common import write_content_to_file
from common.err_code import CommErrCode
from common.exception.common_exception import ErrCodeException
from common.util.exec_utils import exec_mkdir_cmd, check_path_valid


class ClickHouseFileService:

    @staticmethod
    def write_file(file_path, file_content):
        """
        功能描述：如果文件不存在, 则创建文件, 写入数据
        参数：
        @file_path: 文件路径
        @file_content: 文件内容
        返回值：无
        """
        count = 0
        while count < 3:
            count = count + 1
            try:
                if not os.path.exists(file_path):
                    ClickHouseFileService.write_dir_file(file_content, file_path)
                break
            except Exception as e:
                log.error(e, exc_info=True)
                time.sleep(3)

    @staticmethod
    def write_dir_file(file_content, file_path):
        if not check_path_valid(file_path):
            raise ErrCodeException(CommErrCode.PARAMS_IS_INVALID, f"file path[{file_path}] is invalid")
        dirname = os.path.dirname(file_path)
        if not os.path.exists(dirname):
            exec_mkdir_cmd(dirname)
        write_content_to_file(file_path, file_content)

    @staticmethod
    def read_file(file_path):
        """
        功能描述：读取文件
        参数：
        @file_path: 文件路径
        @file_content: 文件内容
        返回值：文件内容
        """
        if not os.path.exists(file_path):
            return ""
        with open(file_path, "r", encoding="utf-8") as f:
            result = f.read()
        return result.strip("\n")

    @staticmethod
    def get_parts_absolute_path(store_path):
        """
        功能描述：根据store路径，获取part路径
        参数：
        @store_path: /disk_path/shadow/{copy_id}{t_db_name}{t_name}/store
        返回值：/disk_path/shadow/{copy_id}{t_db_name}{t_name}/store/xxx/xxx_uuid
        """
        parts_path = None
        if not os.path.exists(store_path):
            return parts_path
        uuid_prefix_path = None
        store_child_names = os.listdir(store_path)
        for store_child_name in store_child_names:
            temp_path = os.path.join(store_path, store_child_name)
            if os.path.isdir(temp_path) and not store_child_name.startswith("."):
                uuid_prefix_path = temp_path
                break
        uuid_prefix_child_names = os.listdir(uuid_prefix_path)
        for uuid_prefix_child_name in uuid_prefix_child_names:
            temp_path = os.path.join(uuid_prefix_path, uuid_prefix_child_name)
            if os.path.isdir(temp_path) and not uuid_prefix_child_name.startswith("."):
                parts_path = temp_path
                break
        return parts_path
